package com.yonyou.brigade.third_parties.bfjr.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.order_center.model.ThirdResult;
import com.yonyou.brigade.order_center.util.YHUtils;
import com.yonyou.brigade.third_parties.bfjr.constant.BfjrConstant;
import com.yonyou.brigade.third_parties.bfjr.dao.BfjrDeptMapper;
import com.yonyou.brigade.third_parties.bfjr.model.BfjrDept;
import com.yonyou.brigade.third_parties.bfjr.service.IBfjrDeptService;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.ybzboot.starter.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BfjrDeptServiceImpl extends ServiceImpl<BfjrDeptMapper, BfjrDept> implements IBfjrDeptService {
    private Logger logger= LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IUserCenterService iUserCenterService;

    @Autowired
    private YHUtils yhUtils;

    @Autowired
    private IBfjrDeptService bfjrDeptService;

    @Value("${bfjr.url.deptAdd}")
    private String deptAddUrl;

    @Value("${bfjr.url.deptEdit}")
    private String deptEditUrl;

    private static final String[] compareFields = {"appId", "deptName", "expDeptId"};



    @Override
    public void sysOrgDept(String tenant, String org, String orgName, JSONObject config) {
        logger.info("同步一级部门");
        BfjrDept bfjrDept = new BfjrDept();
        bfjrDept.setAppId(config.getString("appId"));
        bfjrDept.setDeptName(orgName);
        bfjrDept.setExpDeptId(org);
        bfjrDept.setTenant(tenant);
        Wrapper<BfjrDept> wrapper = new EntityWrapper<>();
        wrapper.eq("expDeptId", org);
        wrapper.eq("tenant", tenant);
        List<BfjrDept> bfjrDeptList = this.selectList(wrapper);
        addOrEdit(bfjrDeptList, config, bfjrDept);
    }

    @Override
    public ThirdResult syncDept(BfjrDept dept, JSONObject config, String operationType){
        String appId = config.getString("appId");
        String url = "" ;
        if (BfjrConstant.DEPT_OPERATION_TYPE_ADD.equals(operationType)) {
            url = deptAddUrl;
        } else if (BfjrConstant.EMPLOYEE_OPERATION_TYPE_EDIT.equals(operationType)) {
            url = deptEditUrl;
        }
        JSONObject requestParam = convertRequestParam(dept, appId);
        logger.info("同步北方假日部门信息" + requestParam.toJSONString());
        String strResult = HttpClientUtil.doPostJsonForm(url,requestParam.toJSONString());
        logger.info("同步北方假日部门信息结果" + strResult);
        if (StringUtil.isNotEmpty(strResult)){
            JSONObject rs = JSONObject.parseObject(strResult);
            if ("0".equals(rs.getString("ret"))){
                return new ThirdResult(true, rs.getString("msg") );
            }else {
                return new ThirdResult(false, rs.getString("msg") );
            }
        }
        return new ThirdResult(false, strResult );
    }


    /**
     * 拼装请求参数
     * @param bfjrDept
     * @param appId
     * @return
     */
    private JSONObject convertRequestParam(BfjrDept bfjrDept, String appId){
        JSONObject param = new JSONObject();
        param.put("appId", appId);
        param.put("deptName", bfjrDept.getDeptName());
        param.put("expDeptId",bfjrDept.getExpDeptId());
        return param;
    }

    /**
     * 新增或修改部门
     * @param bfjrDeptList
     * @param config
     * @param bfjrDept
     */
    private void addOrEdit(List<BfjrDept> bfjrDeptList, JSONObject config, BfjrDept bfjrDept)  {
        if (bfjrDeptList.size() == 0){
            bfjrDeptList.add(bfjrDept);
            for (BfjrDept dept : bfjrDeptList) {
                ThirdResult thirdResult = bfjrDeptService.syncDept(dept, config, BfjrConstant.DEPT_OPERATION_TYPE_ADD);
                if (thirdResult.getSuccess()){
                    this.insert(dept);
                }
            }
        }else {
            //如果已经同步过，检查信息是否有变化，如果有变化则更新
            Map<String, String> compareMap = new HashMap<>();
            Map<String, Object> compareResult = yhUtils.compareFields(compareFields, compareMap, bfjrDeptList.get(0), bfjrDept);
            if (compareResult != null && compareResult.size() > 0) {
                //更新已经同步过的用户信息
                List<BfjrDept> list = new ArrayList<>();
                bfjrDept.setId(bfjrDeptList.get(0).getId());
                ThirdResult thirdResult = bfjrDeptService.syncDept(bfjrDept, config, BfjrConstant.DEPT_OPERATION_TYPE_EDIT);
                if (thirdResult.getSuccess()){
                    this.updateById(bfjrDept);
                }
            }
        }
    }

}
